<template>
  <div>
    <!-- 三級分类搜索 -->
    <el-card style="margin-bottom: 20px">
      <CategorySelect @getcategoryId="getcategoryid" :show="!isShow" />
    </el-card>
    <!-- 展示列表 -->
    <el-card>
      <!-- 属性表格 -->
      <div v-show="isShow">
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-bottom: 10px"
          :disabled="isdisabled"
          @click="addAttr"
          >添加属性</el-button
        >
        <!-- 表格 -->
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值列表"
            width="width"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag
                type="success"
                v-for="(item, index) in scope.row.attrValueList"
                :key="index"
                style="margin: 0 10px"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-edit"
                @click="updataAttr(scope.row)"
                style="margin-right: 5px"
                >修改</el-button
              >
              <!-- 气泡确认框 -->
              <el-popconfirm
                :title="`确定删除${scope.row.attrName}吗？`"
                @onConfirm="deleteAttrInfo(scope.row.id)"
              >
                <el-button
                  type="danger"
                  slot="reference"
                  size="mini"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 修改表格 -->
      <div v-show="!isShow">
        <el-form :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名" prop="attrName">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addValue"
          :disabled="!attrInfo.attrName"
          style="margin-bottom: 10px"
          >添加属性</el-button
        >
        <el-table
          style="width: 50%; margin-bottom: 10px"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="scope">
              <!-- @blur:当元素失去焦点时触发 -->
              <el-input
                size="mini"
                ref="input1"
                placeholder="请输入属性值"
                v-model="scope.row.valueName"
                v-if="scope.row.falg"
                @blur="toLook(scope.row)"
                @keyup.native.enter="toLook(scope.row)"
              ></el-input>
              <span
                v-else
                style="display: block"
                @click="toUpdata(scope.row)"
                >{{ scope.row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-popconfirm
                :title="`确定删除${scope.row.valueName}吗？`"
                @onConfirm="deleteAttrName(scope.$index)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="addOrupdateAttr()"
          :disabled="isBaocun"
          >保存</el-button
        >
        <el-button @click="isShow = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash中的深拷贝
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      attrList: [],
      // 保存id
      id: {},
      // 控制列表页显示与隐藏
      isShow: true,
      // 是否禁用添加属性
      isdisabled: true,
      // 是否可以保存
      isBaocun: true,
      // 收集新增或修改的属性
      attrInfo: {
        attrName: "", // 属性名
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 0,
      },
    };
  },
  methods: {
    addAttr() {
      // 添加之前先格式化需要提交的数据
      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.id.category3Id, //收集三级分类id
        categoryLevel: 3,
      };
      this.isShow = false;
    },
    // 修改属性
    updataAttr(data) {
      this.isShow = false;
      /*
      attrInfo使用了数据的双向绑定，因此如果直接将data赋值给attrInfo的话，修改attrInfo时data也会受到影响
      再者，date的数据结构是对象里面又包含了数组，简单的浅拷贝并不能解决问题，这里得用深拷贝  
       */
      this.attrInfo = cloneDeep(data);
      /*
      点击修改时也要给修改的属性都加上flag字段控制编辑和隐藏，但是这里用直接赋值的方法给attrValueList列表都添加flag，视图并不会生效
      因为这样添加的flag并不是响应式数据
      */
      this.attrInfo.attrValueList.forEach((element) => {
        // 给对象添加响应式数据
        this.$set(element, "falg", false);
      });
      this.isBaocun = this.attrInfo.attrValueList.length > 0 ? false : true;
    },
    getcategoryid(id) {
      this.id = id;
      const { category1Id, category2Id, category3Id } = this.id;
      // 当三个id都有时才能添加属性和展示数据列表地
      if (category3Id && category1Id && category2Id) {
        this.isdisabled = false;
        this.getAttrList(category1Id, category2Id, category3Id);
      } else {
        this.isdisabled = true;
      }
    },
    // 获取分类数据
    async getAttrList(id1, id2, id3) {
      const res = await this.$API.attr.reqAttrInfoList(id1, id2, id3);
      if (res.code == 200) {
        this.attrList = res.data;
      }
    },
    // 添加/修改属性值
    addValue() {
      // 向属性值列表里插入空数据，通过psuh方法插入的数据为响应式数据
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, // 修改是有id的，添加没有id就是undefined
        valueName: "",
        falg: true, // 控制输入框的显示与隐藏
      });
      // 让新增的input框自动聚焦，数组最后一位
      this.$nextTick(() => {
        //  获取到对应的input框实现聚焦
        this.$refs.input1.focus();
      });
    },
    // 失去焦点或者回车
    toLook(row) {
      // 添加之前判断
      // 输入的值不能为空串 trim()：去除字符串首尾的空格
      if (row.valueName.trim() == "") {
        this.$message({
          type: "warning",
          message: "请输入属性值",
        });
        // 不能保存
        this.isBaocun = true;
        return;
      }
      // 判断添加的数据在列表里是否重复
      // some(): 检测数组中的每一个元素，如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测。
      let isRepat = this.attrInfo.attrValueList.some((item) => {
        // 不和自己比较
        if (row !== item) {
          return row.valueName == item.valueName;
        }
      });
      if (isRepat) {
        this.$message({
          type: "warning",
          message: "不能添加重复属性值",
        });
        this.isBaocun = true;
        return;
      }
      // 可以报错
      this.isBaocun = false;
      // input框隐藏
      row.falg = false;
    },
    // 点击属性值
    toUpdata(row) {
      row.falg = true;
      /*
      点击span的时候页面会进行重绘生成input框，
      这个过程是需要时间的，我们没法点击就立即获取到input框的节点
      $nextTick()页面渲染完成后执行一次回调
      */
      this.$nextTick(() => {
        //  获取到对应的input框实现聚焦
        this.$refs.input1.focus();
      });
    },
    // 点击删除再点击气泡框的确认按钮是触发
    async deleteAttrInfo(attrId) {
      try {
        const res = await this.$API.attr.reqDeleteAttr(attrId);
        this.$message({
          type: "success",
          message: "删除成功",
        });
      } catch (error) {
        return "失败";
      }
      // 重新获取数据
      const { category1Id, category2Id, category3Id } = this.id;
      this.getAttrList(category1Id, category2Id, category3Id);
    },
    // 删除属性值
    deleteAttrName(index) {
      this.attrInfo.attrValueList.splice(index, 1);
      // 判断保存是否可以激活
      this.isBaocun = this.attrInfo.attrValueList.length > 0 ? false : true;
    },
    // 保存按钮
    async addOrupdateAttr() {
      // 整理数据
      // 过滤掉名字为空白的属性值
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(
        (item) => {
          if (item.valueName !== "") {
            //  删除掉自定义的falg字段
            delete item.falg;
            return true;
          }
        }
      );
      // 发请求
      const res = await this.$API.attr.reqSaveAttrInfo(this.attrInfo);
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: "保存成功",
        });
        // 跳转列表页重新获取数据
        this.isShow = true;
        const { category1Id, category2Id, category3Id } = this.id;
        this.getAttrList(category1Id, category2Id, category3Id);
      }
    },
  },
};
</script>

<style scoped>
</style>
